package com.eleven.trades.serverimpl;

import com.eleven.trades.entity.User;
import com.eleven.trades.error.BusinessException;
import com.eleven.trades.mapper.UserMapper;
import com.eleven.trades.result.ResultCode;
import com.eleven.trades.server.UserServer;
import com.eleven.trades.utils.CommonUtils;
import com.eleven.trades.utils.ValidationResult;
import com.eleven.trades.utils.ValidatorImpl;
import com.eleven.trades.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServerImpl implements UserServer {
    @Autowired
    private ValidatorImpl validator;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void register(UserVo userVo) throws BusinessException {
        //校验参数格式是否正确
        ValidationResult result = validator.validate(userVo);
        if(result.isHasErrors())
        {
            throw new BusinessException(ResultCode.PARAM_FORMAT_ERROR);
        }
        //查询用户中手机号码是否已存在

        //对密码加密
        String password = CommonUtils.md5(userVo.getUserPassword());
        userVo.setUserPassword(password);
        //uservo转userdo
        User user = new User();
        BeanUtils.copyProperties(userVo,user);
        try{
//            userMapper.insertSelective(user);
            userMapper.insert(user);
        }
        catch (Exception e)
        {
            throw new BusinessException(ResultCode.DATABASE_INSERT_FAIL,"注册失败");
        }
//        userVo.setUserId(user.getUserId());
    }

    @Override
    public void modifyInfo() {

    }

    @Override
    public UserVo getUserInfo(Integer id) {
        User user = userMapper.selectById(id);

        UserVo userVo = new UserVo();

        BeanUtils.copyProperties(user,userVo);
        return userVo;
    }


}
